package cn.tedu.ivos.base.security;

import cn.tedu.ivos.user.mapper.UserMapper;
import cn.tedu.ivos.user.pojo.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

/**
 * 自定义用户详情业务类，需要实现SpringSecurity提供的UserDetailsService的接口
 */
@Service
@Slf4j
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    /**
     * 根据用户名查询用户详情
     * @param username 用户名
     * @return CustomUserDetails对象，包含用户详情信息
     * @throws UsernameNotFoundException  如果用户不存在，抛出异常
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("根据用户名查询用户详情,",username);
        //检查用户名是否为空，如果为空抛出异常
        if (username==null)
            throw new UsernameNotFoundException("用户不能为空");
        //如果不为空，去数据库查询对应的用户信息
        UserVO userVO = userMapper.selectByUsername(username);
        //如果用户信息不存在，抛出异常
        if(userVO==null)
            throw new UsernameNotFoundException("没有该用户");
        //userVO对象存在，将用户信息赋值到CustomUserDetails对象中
        //准备一个CustomUserDetails对象
        CustomUserDetails userInfo = new CustomUserDetails();
        userInfo.setUserId(userVO.getId());
        userInfo.setUsername(userVO.getUsername());
        userInfo.setPassword(userVO.getPassword());
        //用户的权限集合
        Set<GrantedAuthority> authoritySet = new HashSet<>();
        //给一个假权限就可以，没有具体的权限但是不能为空，为空会报错
        GrantedAuthority authority = new SimpleGrantedAuthority("test");
        authoritySet.add(authority);
        userInfo.setAuthorities(authoritySet);
        //千万要记得返回
        return userInfo;
    }
}
